package com.atguigu.gmall.seckill.schedule;


import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.seckill.service.SeckillCacheService;
import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class SeckillGoodUpTask {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SeckillGoodsService seckillGoodsService;

    @Autowired
    SeckillCacheService seckillCacheService;

    /**
     * 把后台设置的当天要秒杀的商品数据预热缓存到redis
     * 1、  6:00~00:00
     * 秒 分 时  日 月 周
     */
//    @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(cron = "0 * * * * ?")
    public void upSeckillGoods(){
        log.info("正在预热秒杀缓存....");
        //1、查到当天需要上架的所有商品
        List<SeckillGoods> goods = seckillGoodsService.getTodaySeckillGoods();

        //2、给redis存一份
        seckillCacheService.cacheSaveGoods(goods);


        //3、本地同步一份
        seckillCacheService.syncLocalCache(goods);


        //4、在redis中维护当天参与的所有秒杀商品的库存数量
        for (SeckillGoods good : goods) {
            String skuStockKey = RedisConstant.SECKILL_GOOD_STOCK + DateUtil.formatDate(new Date())+":" + good.getSkuId();
            redisTemplate.opsForValue().set(skuStockKey,good.getStockCount().toString());
        }



    }

}
